<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <%@include file="include/header.jsp"%>
    <title>角色维护</title>
    <script src="static/vue/vue.min.js"></script>
    <link rel="stylesheet" href="static/ztree/zTreeStyle.css">
    <script type="text/javascript" src="static/ztree/jquery.ztree.all-3.5.min.js"></script>
    <style>
        .m-page {
            /* 设置文字不被选中 */
            -webkit-user-select:none;
            -moz-user-select:none;
            -ms-user-select:none;
            user-select:none;
            /* 设置鼠标滑过样式变手 */
            cursor: pointer;
        }
        .modal-body {
            padding: 20px;
        }
        /* 调整一下每个菜单项之间的间距 */
        .ztree li {
            margin-top: 5px !important;
        }
        /* 调整一下菜单名称和图标之间的间隔 */
        .ztree .glyphicon {
            padding-right: 5px;
        }
        /* 设置添加，编辑，删除三个按钮之间的间距 */
        .m-addBtn, .m-editBtn, .m-rmBtn {
            margin-left:10px;padding-top:0px;
        }
    </style>
</head>

<body>

<%@include file="include/nav.jsp"%>

<div class="container-fluid">
    <div class="row">
        <%@include file="include/sidebar.jsp"%>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
            <!-- 在此处绘制页面 -->
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">
                        <i class="glyphicon glyphicon-th"></i> 数据列表
                    </h3>
                </div>
                <%-- 从这里开始被Vue接管 --%>
                <div id="m-root" class="panel-body">
                    <div class="form-inline" style="float:left;">
                        <div class="form-group has-feedback">
                            <div class="input-group">
                                <div class="input-group-addon">查询条件</div>
                                <input class="form-control has-success" type="text" placeholder="请输入查询条件" v-model="temp.query" @keyup.enter="updateQuery()">
                            </div>
                        </div>
                        <button class="btn btn-warning" @click="updateQuery()">
                            <i class="glyphicon glyphicon-search"></i> 查询
                        </button>
                    </div>
                    <button class="btn btn-danger" style="float:right; margin-left:10px;" @click="deleteList()">
                        <i class="glyphicon glyphicon-remove"></i> 删除
                    </button>
                    <button class="btn btn-primary" style="float:right;" @click="openInsertDialog()">
                        <i class="glyphicon glyphicon-plus"></i> 新增
                    </button>
                    <br>
                    <hr style="clear:both;">
                    <%-- 渲染的表格 --%>
                    <div v-show="info.list.length > 0" class="table-responsive">
                        <table class="table  table-bordered">
                            <thead>
                                <tr>
                                    <th width="35">#</th>
                                    <th width="30">
                                        <input type="checkbox" v-model="selectAllBtn">
                                    </th>
                                    <th>名称</th>
                                    <th width="100">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(item, index) in info.list">
                                    <td v-text="index+1"></td>
                                    <td><input type="checkbox" :value="item.id" v-model="checkList"></td>
                                    <td v-text="item.name"></td>
                                    <td>
                                        <button type="button" class="btn btn-success btn-xs" @click="openAssignAuthDialog(item.id)" title="分配权限">
                                            <i class="glyphicon glyphicon-check"></i>
                                        </button>
                                        <button type="button" class="btn btn-primary btn-xs" @click="openUpdateDialog(item)" title="编辑">
                                            <i class="glyphicon glyphicon-pencil"></i>
                                        </button>
                                        <button type="button" class="btn btn-danger btn-xs" @click="deleteById(item)" title="删除">
                                            <i class="glyphicon glyphicon-remove"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="6" align="center">
                                        <ul class="pagination m-page">
                                            <%-- 上一页 --%>
                                            <li :class="{'disabled': !info.hasPreviousPage}">
                                                <a @click="prePage()">上一页</a>
                                            </li>
                                            <%-- 页码 --%>
                                            <li v-for="item in info.navigatepageNums" :class="{'active': item==info.pageNum}">
                                                <a @click="toPage(item)">{{item}}</a>
                                            </li>
                                            <%-- 下一页 --%>
                                            <li :class="{'disabled': !info.hasNextPage}">
                                                <a @click="nextPage()">下一页</a>
                                            </li>
                                        </ul>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <%-- 没有数据的提示 --%>
                    <div v-show="info.list.length < 1" style="text-align: center">查询结果为空</div>

                    <%-- 添加、编辑的模态框 --%>
                    <div id="insertAndUpdateDialog" class="modal fade" tabindex="-1">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <%-- Title --%>
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title">{{dialog.title}}</h4>
                                </div>
                                <%-- Body --%>
                                <div class="modal-body">
                                    <div class="form-group">
                                        <label for="exampleInputEmail1">{{dialog.label}}</label>
                                        <input type="email" class="form-control" id="exampleInputEmail1" v-model="dialog.value">
                                    </div>
                                </div>
                                <%-- Footer --%>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                    <button type="button" class="btn btn-primary" @click="dialog.callBack()">确定</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <%-- 分配权限的模态框 --%>
                    <div id="assignAuthDialog" class="modal fade" tabindex="-1">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <%-- Title --%>
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title">分配权限</h4>
                                </div>
                                <%-- Body --%>
                                <div class="modal-body">
                                    <ul id="zTree" class="ztree"></ul>
                                </div>
                                <%-- Footer --%>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-primary" @click="submitAssignAuth()">分配权限</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    new Vue({
        el: "#m-root",
        data: {
            temp: {  // temp中包含的都是临时变量
                query: "",
                roleId: null
            },
            query: "",
            current: 1,
            size: null,
            info: { list: [] },
            checkList: [],
            selectAllBtn: false,
            dialog: { title: "", label: "", value: "", temp: "", callBack: null },
            tree: {
                settings: null,
                authList: [],
                role_id: null
            }
        },
        // 声明周期函数
        created(){
            // 获取角色信息初始化页面
            this.getPageInfo();
            // 初始化tree相关设置
            this.initTree();
        },
        methods: {
            // 发起请求
            req( type, url, data = null ){
                return new Promise((resolve, reject) => {
                    $.ajax({
                        type: type,
                        url: url,
                        data: data,
                        dataType: "json",
                        success(res){
                            // 成功返回就回调，否则提示异常信息，异常信息由服务端提供
                            if ( res.code === 100 ){
                                resolve(res);
                            } else {
                                layer.msg(res.msg);
                                reject(res);
                            }
                        },
                        error(err){
                            // 走到这里就说明请求失败了，执行失败逻辑
                            layer.msg("请求服务端失败！状态码为：" + err.status + "，详细信息为：" + err.statusText);
                            reject(err);
                        }
                    });
                });
            },
            // 获取到PageInfo对象
            getPageInfo(){
                let param = {
                    "query": this.query,
                    "current": this.current,
                    "size": this.size
                };
                this.req("get", "role/get/page/info.json", param).then(res=>{
                    this.info = res.data.info;
                });
                // 每当页面的数据重新获取后都要重置一下全选状态
                this.selectAllBtn = false;
            },
            // 更新模糊查询关键字
            updateQuery(){
                this.query = this.temp.query;
                this.current = 0;
                this.getPageInfo();
                return false;
            },
            // 前往目标页码
            toPage( current ){
                this.current = current;
                this.getPageInfo();
            },
            // 上一页
            prePage(){
                if ( this.info.hasPreviousPage ){
                    this.current--;
                    this.getPageInfo();
                } else layer.msg("不能再往前啦");
            },
            // 下一页
            nextPage(){
                if ( this.info.hasNextPage ){
                    this.current++;
                    this.getPageInfo();
                } else layer.msg("不能再往后啦");
            },
            // 打开新增模态框
            openInsertDialog(){
                this.dialog = {
                    title: "添加角色",
                    label: "请输入角色名称：",
                    value: "",
                    callBack: ()=>{
                        this.req("post", "role/insert.json", { name: this.dialog.value }).then( res=>{
                            if ( res.data.count === 1 ){
                                // 弹出成功提示，并且将数据跳转到最后一行并刷新，让客户看到添加后的效果
                                layer.msg(res.msg);
                                this.current = this.info.pages;
                                this.getPageInfo();
                            } else layer.msg("添加失败！请稍后刷新页面重试");
                            // 关闭模态框
                            $("#insertAndUpdateDialog").modal("hide");
                        });
                    }
                };
                $("#insertAndUpdateDialog").modal("show");
            },
            // 打开编辑模态框
            openUpdateDialog(role){
                this.temp.roleId = role.id;
                this.dialog = {
                    title: "编辑角色",
                    label: "将角色【" + role.name + "】修改为：",
                    value: "",
                    callBack: ()=>{
                        let param = { id: this.temp.roleId, name: this.dialog.value };
                        this.req("post", "role/update.json", param).then(res=>{
                            if ( res.data.count === 1 ){
                                // 弹出成功提示并刷新表格数据，让客户看到效果
                                layer.msg(res.msg);
                                this.getPageInfo();
                            } else layer.msg("操作失败！请稍后刷新页面重试");
                            $("#insertAndUpdateDialog").modal("hide");
                        });
                    }
                };
                $("#insertAndUpdateDialog").modal("show");
            },
            deleteById(item){
                let options = {
                    title: "提示",
                    btn: ['删除','取消']
                };
                layer.confirm("确定要删除角色【" + item.name + "】吗？", options, ()=>{
                    // 清空数组后添加被删除的目标ID执行批量删除操作
                    this.checkList = [];
                    this.checkList.push(item.id);
                    this.actionDelete();
                })
            },
            // 批量删除
            deleteList(){
                if ( this.checkList.length > 0 ){
                    let options = {
                        title: "提示",
                        btn: ['删除','取消']
                    };
                    layer.confirm("确定要删除这" + this.checkList.length + "个角色吗？", options, ()=>{
                        this.actionDelete();
                    })
                } else layer.msg("请至少选择一个进行删除");
            },
            // 提交删除
            actionDelete(){
                // 提交删除操作，然后重置复选框并刷新页面数据
                this.req("post", "role/delete/list/by/id.json", { "listId": JSON.stringify(this.checkList) }).then(res=>{
                    layer.msg(res.msg);
                    this.checkList = [];
                    this.getPageInfo();
                });
            },
            // 获取权限列表
            getAuthList(){
                this.req("get", "assign/get/all/auth.json").then(res=>{
                    this.tree.authList = res.data.authList;
                });
            },
            // 初始化权限树的信息
            initTree() {
                // 获取权限列表
                this.getAuthList();
                // 初始化zTree的配置对象
                this.tree.settings = {
                    data: {
                        // 使用简单tree，设置父节点为categoryId
                        simpleData: { enable: true, pIdKey: "categoryId" },
                        // title作为名称显示在true中
                        key: { name: "title" }
                    },
                    // 显示checkbox复选框
                    check: { enable: true }
                };
            },
            // 打开分配权限的模态框
            openAssignAuthDialog( id ) {
                this.tree.role_id = id;
                // 渲染zTree然后打开模态框
                $.fn.zTree.init($("#zTree"), this.tree.settings, this.tree.authList);
                this.req("get", "assign/get/assign/auth/by/roleId.json", { id } ).then( res=>{
                    // 这里获取zTree对象进行全部展开一定要等模态框打开之后再执行
                    $("#assignAuthDialog").modal("show");
                    let zTree = $.fn.zTree.getZTreeObj("zTree");
                    zTree.expandAll(true);
                    res.data.assignList.forEach((id)=>{
                        let node = zTree.getNodeByParam("id", id);
                        // node：需要设置的节点，true：是否选中，false：是否联动
                        zTree.checkNode(node, true, false);
                    })
                })
            },
            // 提交权限分配的事件
            submitAssignAuth(){
                let list = [];
                $.fn.zTree.getZTreeObj("zTree").getCheckedNodes().forEach(item=>list.push(item.id));
                let param = { id: this.tree.role_id, authList: JSON.stringify(list) };
                this.req("post", "assign/do/role/assign/auth.json", param).then(res=>{
                    layer.msg(res.msg);
                    $("#assignAuthDialog").modal("hide");
                });
            },
        },
        watch: {
            // 监听全选复选框，一旦被选择中就遍历所有ID插入到集合中实现全选，反之也是一样
            selectAllBtn(){
                if ( this.selectAllBtn ){
                    this.info.list.forEach( item=>this.checkList.push(item.id) );
                } else this.checkList = [];
            }
        }
    })
</script>
</html>